package com.xue.springcloud.controller;

import com.alibaba.fastjson.JSONObject;
import com.xue.springcloud.pojo.Dept;
import com.xue.springcloud.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

//提供Restful服务  即接口服务
@RestController
@RequestMapping("dept")
public class DeptController {
    @Autowired
    private DeptService deptService;
    @Autowired
    private DiscoveryClient discoveryClient;

//    @RequestMapping("/dept/add")
    @RequestMapping("add")
    public boolean addDept(@RequestBody  Dept dept){
        return deptService.addDept(dept);
    }

    @GetMapping("get/{id}")
    public Dept queryById(@PathVariable("id") Long id){
        return deptService.queryById(id);
    }
    @GetMapping("list")
    public List<Dept> queryByAll(){
        List<Dept> list =  deptService.queryByAll();
        return list;
    }
    @GetMapping("getList")
    public JSONObject getList(){
        JSONObject object = new JSONObject();
        object.put("1","aadas");
        object.put("2","aadas");
        object.put("3","aadas");
        object.put("4","aadas");
        return object;
    }

    /**
     * 获取到注册进来的微服务的一些信息（扩展）
     * 注意：获取信息的前提需要在启动类上添加    @EnableDiscoveryClient  即服务发现注解
     */
    @RequestMapping("getDiscovery")
    private Object discovery(){

        //获取微服务列表清单
        List<String> services = discoveryClient.getServices();
        System.out.println("discovery=>services"+services);

        //通过具体的微服务id（即applicationName）获取微服务信息
        List<ServiceInstance> instances = discoveryClient.getInstances("SPRINGCLOUD-PROVIDER-DEPT");
        for (ServiceInstance instance:instances) {
            System.out.println(
                    instance.getHost()+"\t"+
                    instance.getPort()+"\t"+
                    instance.getUri()+"\t"+
                    instance.getServiceId()
            );
        }
        return discoveryClient;
    }
}
